<template>
  <div class="product-detail">
    <!-- 商品主区域 -->
    <div class="product-main">
      <!-- 左侧图片 -->
      <div class="product-images">
        <img
          :src="`http://117.72.153.227/image/${product.fileName || ''}`"
          :alt="product.productName"
          class="main-image"
        />
      </div>

      <!-- 右侧信息区 -->
      <div class="product-info">
        <h1 class="product-title">{{ product.productName }}</h1>
        <div class="price-section">
          <span class="current-price">¥{{ product.price.toFixed(2) }}</span>
          <span class="stock">库存: {{ product.stock }}件</span>
        </div>

        <div class="description">
          <h3>商品描述</h3>
          <p>{{ product.description }}</p>
        </div>

        <!-- 数量选择器 -->
        <div class="quantity-selector">
          <span>数量:</span>
          <button class="btn-quantity" @click="decreaseQuantity">-</button>
          <input
            type="number"
            v-model.number="quantity"
            min="1"
            :max="product.stock"
            @change="validateQuantity"
          />
          <button class="btn-quantity" @click="increaseQuantity">+</button>
          <span class="max-tip" v-if="product.stock > 0">
            (最多可购{{ product.stock }}件)
          </span>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn-cart" @click="addToCart" v-if="isHaveStoke">
            加入购物车
          </button>
          <button class="btn-cart-nullStoke" v-if="!isHaveStoke">
            商品已售空
          </button>
          <button class="btn-collect" @click="toggleCollect(product.id)">
            <i :class="isCollected ? 'icon-collected' : 'icon-uncollect'"></i>
            {{ isCollected ? "已收藏" : "收藏" }}
          </button>
        </div>
      </div>
    </div>

    <!-- 商品详情描述 -->
    <div class="product-description">
      <h2>详细介绍</h2>
      <div class="detail-content">
        <p>{{ product.description }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ProductDetail",
  data() {
    return {
      currentImage: "",
      isCollected: false,
      quantity: 1, // 默认数量为1
      isHaveStoke: false,
      product: {
        id: 0,
        productName: "",
        description: "",
        price: 0,
        stock: 0,
        fileName: "",
      },
    };
  },
  created() {
    const productId = this.$route.params.id;
    console.log("商品ID:", productId);

    if (productId) {
      this.loadProduct(productId);
    } else {
      console.error("未获取到商品ID");
    }
  },
  mounted() {
    this.checkCollectionStatus();
  },
  methods: {
    checkCollectionStatus() {
      this.isCollected =
        localStorage.getItem(`collected_${this.product.id}`) === "true";
    },
    async toggleCollect(productId) {
      const token = sessionStorage.getItem("token");
      if (!token) {
        this.$message.error("用户未登录");
        return;
      }
      const response = await axios.post(
        `/api/product/addFavorite/${productId}`
      );
      console.log(response);
      if (response.data.code === "400" || response.data.code === "401") {
        this.$message.error(response.data.msg);
      } else if (response.data.code === 5001) {
        this.$message.error("添加失败");
      } else {
        this.$message.success("收藏添加成功");
      }
    },
    // 增加数量
    increaseQuantity() {
      if (this.quantity < this.product.stock) {
        this.quantity++;
      } else {
        this.$message({
          title: "提示",
          message: `已达到最大库存量 ${this.product.stock} 件`,
          type: "warning",
        });
      }
    },
    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },
    // 验证数量输入
    validateQuantity() {
      if (this.quantity < 1) {
        this.quantity = 1;
      } else if (this.quantity > this.product.stock) {
        this.quantity = this.product.stock;
        this.$message({
          title: "提示",
          message: `数量已调整为最大库存量 ${this.product.stock} 件`,
          type: "warning",
        });
      }
    },
    async addToCart() {
      try {
        const token = sessionStorage.getItem("token");
        if (!token) {
          this.$message.error("用户未登录");
          return;
        }

        const payload = {
          productId: Number(this.product.id),
          productName: this.product.productName,
          price: Number(this.product.price),
          quantity: Number(this.quantity),
          fileName: this.product.fileName,
          cost: Number(this.product.price * this.quantity),
        };

        // 发送请求
        const response = await axios.post(
          `/api/shoppingCart/addProductToCart`,
          payload,
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );

        //  处理响应
        if (response.data.code === 200) {
          this.$message.success("添加成功");
          // 重新获取最新购物车
          await this.$store.dispatch("fetchCart");
        }
      } catch (error) {
        console.error("添加购物车失败:", {
          error: error.response?.data || error.message,
          request: error.config,
        });
        this.$message.error(error.response?.data?.message || "添加失败");
      }
    },
    async loadProduct(id) {
      try {
        const response = await axios.get(`/api/product/getProductById/${id}`);
        console.log("商品详情响应", response);

        if (response.data && response.data.product) {
          this.product = response.data.product;
          if (this.product.fileName) {
            this.currentImage = `http://117.72.153.227/image/${this.product.fileName}`;
          }
          if (this.product.stock === 0) {
            this.isHaveStoke = false;
          } else {
            this.isHaveStoke = true;
          }
          // 重置数量为1
          this.quantity = 1;
        } else {
          throw new Error("商品数据格式不正确");
        }
      } catch (error) {
        console.error("加载商品失败:", error);
        this.$message({
          title: "错误",
          message: "加载商品信息失败，请稍后重试",
          type: "error",
        });
      }
    },
  },
};
</script>

<style scoped>
.product-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.product-main {
  display: flex;
  gap: 30px;
  margin-bottom: 40px;
}

.product-images {
  flex: 1;
  display: flex;
  gap: 10px;
}

.main-image {
  width: 400px;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}

.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.thumbnail-list img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
  cursor: pointer;
  opacity: 0.7;
  transition: all 0.3s;
}

.thumbnail-list img:hover,
.thumbnail-list img.active {
  opacity: 1;
  border-color: #f56c6c;
}

.product-info {
  flex: 2;
}

.product-title {
  font-size: 22px;
  margin: 0 0 10px;
  color: #333;
}

.category-path {
  color: #999;
  font-size: 14px;
  margin-bottom: 15px;
}

.price-section {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.current-price {
  color: #f56c6c;
  font-size: 28px;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 16px;
}

.stock {
  color: #666;
  font-size: 14px;
}

.description {
  margin: 25px 0;
  color: #666;
  line-height: 1.6;
}

.description h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.btn-cart {
  padding: 12px 25px;
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-cart-nullStoke {
  padding: 12px 25px;
  background: gra;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-cart:hover {
  background: #e05b5b;
}

.btn-collect {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 25px;
  background: #fff;
  border: 1px solid #f56c6c;
  color: #f56c6c;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-collect:hover {
  background: #f56c6c;
  color: white;
}

.icon-uncollect::before {
  content: "♡";
  font-size: 18px;
}

.icon-collected::before {
  content: "♥";
  font-size: 18px;
  color: #f56c6c;
}

.product-description {
  padding: 20px 0;
  border-top: 1px solid #eee;
}

.product-description h2 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.detail-content {
  color: #666;
  line-height: 1.8;
}

.detail-content p {
  white-space: pre-line;
  margin: 10px 0;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin: 20px 0;
  gap: 10px;
}

.quantity-selector span {
  font-size: 14px;
  color: #666;
}

.quantity-selector input {
  width: 60px;
  height: 32px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.btn-quantity {
  width: 32px;
  height: 32px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-quantity:hover {
  background: #eee;
}

.max-tip {
  color: #999;
  font-size: 12px;
}

.quantity-selector input[type="number"] {
  -moz-appearance: textfield;
  /* Firefox */
}

.quantity-selector input[type="number"]::-webkit-inner-spin-button,
.quantity-selector input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  /* Chrome, Safari, Edge */
  margin: 0;
  /* 解决部分浏览器残留的边距 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .quantity-selector {
    flex-wrap: wrap;
  }

  .max-tip {
    width: 100%;
    margin-top: 5px;
  }
}
</style>